# -*- coding: utf-8 -*-

import os
import sys
from jinja2 import Environment, FileSystemLoader
sys.path.insert(0, "/pitrix/lib/pitrix-installer-common")
from log.logger import logger
from misc.exec_cmd import safe_exec_cmd


envs = {}

def jinja2_dump(template_file_dir, template_file_name, configurations, dump_file):
    env = envs.get(template_file_dir, None)
    if not env:
        env = Environment(loader=FileSystemLoader(template_file_dir, 'utf-8'))
        envs[template_file_dir] = env

    templeat_file = "{0}/{1}".format(template_file_dir, template_file_name)
    if not os.path.isfile(templeat_file):
        logger.error("The template file [{0}] does not exist, please check it!".format(templeat_file))
        sys.exit(1)

    template = env.get_template(template_file_name)
    logger.info("Writing the dump file [{0}] ...".format(dump_file))
    stream = template.stream(configurations)
    if not os.path.isdir(os.path.dirname(dump_file)):
        safe_exec_cmd("mkdir -p {0}".format(os.path.dirname(dump_file)))
    stream.dump(dump_file)
    logger.info("Writing the dump file [{0}] successfully.".format(dump_file))

